import { logMgr } from "../Manager/LogMgr";
import { BaseView } from "./BaseView";
import { CycleLifeFlag } from "./CycleLifeFlag";


/**
 * 生命周期
 * onClickEventInit
 * onCustomEventInit 
 * onPreShow
 */

interface View {
    [propName: string]: cc.Node;
}

export abstract class BaseItem extends BaseView {
    //////////////////////////////////////////////////////框架相关
    private _param: any = null
    protected get CustomParam() { return this._param }

    protected abstract onPreShow(): void

    protected onClickEventInit() { }
    protected onCustomEventInit() { }

    public readonly init = (param: any) => {
        if (this.checkCycleLifeFlag(CycleLifeFlag.PreLoad)) return
        this.setCycleLifeFlag(CycleLifeFlag.PreLoad)
        this._param = param
        this.onClickEventInit()
        this.onCustomEventInit()
    }
    protected readonly onLoad = () => { }

    protected readonly start = async () => {
        if (this.checkCycleLifeFlag(CycleLifeFlag.Opening)) return
        this.setCycleLifeFlag(CycleLifeFlag.Opening | CycleLifeFlag.Show)
        this.onPreShow()
    }

    protected readonly onDestroy = () => {
        // 不做处理了 在 dispose 处理
        !this.checkCycleLifeFlag(CycleLifeFlag.Destroy) && logMgr.error(`[${this.name}] CycleAlive is true when onDestroy called`)
    }

    public readonly dispose = () => {
        if (this.checkCycleLifeFlag(CycleLifeFlag.Destroy)) return
        this.setCycleLifeFlag(CycleLifeFlag.Destroy)
        this.onDispose()
    }

    //////////////////////////////////////////////////////功能拓展
    private loadObject(root: cc.Node, path: string, view: View) {
        for (let i = 0; i < root.childrenCount; i++) {
            view[root.children[i].name] = root.children[i];
            this.loadObject(root.children[i], path + root.children[i].name + "/", view);
        }
    }

    protected loadAllObject(root: cc.Node) {
        let view: View = {};
        this.loadObject(root, "", view)
        return view;
    }

    protected getAutoUI<T extends cc.Component>(type: { prototype: T }): T {
        return this.node.getComponent(type)
    }
}